import { SelectQueryBuilder } from "xl-ts-plugins/typeorm";
import { dateTimeValidator } from './validator'
import { ApiModel, ApiModelProperty, DataType } from 'xl-ts-plugins/swagger'

/**
 * 请求列表参数
*/

export const ListParamsModelName = 'ListParams'

@ApiModel({ name: ListParamsModelName, description: '列表请求参数', isCreateTag: false })
export class ListParams {

  @ApiModelProperty({ description: '第几页', type: DataType.Number, default: 1 })
  page: number;


  @ApiModelProperty({ description: '一页有多少条数据', type: DataType.Number, default: 10 })
  limit: number;


  @ApiModelProperty({ description: '是否分页', type: DataType.Boolean, default: true })
  isPage: boolean;


  @ApiModelProperty({ description: '开始时间', type: DataType.String, default: '' })
  startTime: string;


  @ApiModelProperty({ description: '结束时间', type: DataType.String, default: '' })
  endTime: string;
}

export function ListParamsBuilder(target: { [key: string]: number | boolean | string }): ListParams {
  const result = new ListParams()

  result.page = parseInt(String(target.page)) >= 1 ? parseInt(String(target.page)) : 1

  result.limit = parseInt(String(target.limit)) >= 1 ? parseInt(String(target.limit)) : 10

  result.isPage = target.isPage !== 'false' && target.isPage !== false

  result.startTime = dateTimeValidator(String(target.startTime)) ? String(target.startTime) : ''

  result.endTime = dateTimeValidator(String(target.endTime)) ? String(target.endTime) : ''

  return result
}

export function ListParamsQueryBuilder <T extends Object>(sqb: SelectQueryBuilder<T>, target: ListParams | { [key: string]: number | boolean | string }, timeProperty?: string): SelectQueryBuilder<T> {
  const listParams = target instanceof ListParams ? target: ListParamsBuilder(target)

  // 分页
  if (listParams.isPage) {
    sqb
      .offset((listParams.page - 1) * listParams.limit)
      .limit(listParams.limit)
  }

  // 时间范围
  if (timeProperty && listParams.startTime) {
    sqb.andWhere(`unix_timestamp(${timeProperty}) >= unix_timestamp('${listParams.startTime}')`)
  }

  if (timeProperty && listParams.endTime) {
    sqb.andWhere(`unix_timestamp(${timeProperty}) <= unix_timestamp('${listParams.endTime}')`)
  }

  return sqb
}
